<style scoped>
  .map-box {
    height: 100%;
    position: relative;
  }
  .device{
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    width: 400px;
    background: #fcfcfc;
    color:#000;
    font-size: 14px;
  }
  .calendarBox{
    margin-top: 20px;
  }
  .time{
    margin-top: 20px;
    padding: 20px;
  }
  .el-date-editor.el-input {
    width: 45%;
  }
  .el-input{
    width: 92%;
    margin-bottom: 10px;
  }
  .selectTitle{
    font-weight: bold;
    display: inline-block;
    margin-bottom: 10px;
  }
  .back{
    padding-left: 30px;
    margin-top: 20px;
    cursor: pointer;
  }
  .infor{
    margin-top:20px;
    padding-left: 30px;
  }
  .play{
    position: absolute;
    bottom: 30px;
    width: 650px;
    height: 70px;
    border-radius: 6px;
    background: rgba(0,0,0,.7);
    left:50%;
    transform: translate(-50%,0);
    color:#fff
  }
  .play-box{
    display: flex;
    padding: 0 10px;
  }
  .block{
    width: 70%;
    margin: 0 10px;
  }
  .text{
    line-height: 70px;
  }
  .optbtn{
    margin-top: 15px;
  }
  #allmap{
    margin-left:400px
  }
  .trackdate   .el-input.is-disabled .el-input__inner{
    color:#01b46a!important;
  }
  .distance-time{
    padding: 10px 20px;
    font-size: 15px;
    line-height: 2;
  }
</style>
<template>
  <div class="map-box" v-loading.body="listLoading" element-loading-text="Loading">
    <mainmap v-on:initmap="initmap"></mainmap>
    <div class="mapOptionBtn">
      <el-button class="countinfo" @click="goback">返回监控</el-button>
      <el-button class="countinfo" @click="refresh">刷新</el-button>
    </div>
    <div class="device trackdate">
      <div class="infor">
        <p>设备名称：</p>
        <p>设备IMEI：{{this.$route.query.imei}}</p>
      </div>
      <div class="calendarBox">
        <Calendar ref="Calendar" v-on:choseDay="clickDay" v-on:changeMonth="changeDate" :markArray="markArray"></Calendar>
      </div>
      <div class="time">
        <span class="selectTitle">
          选择轨迹时间：
        </span>
        <el-input
          placeholder="请输入内容"
          v-model="date"
          :disabled="true">
        </el-input>
        <el-time-select
          placeholder="起始时间"
          v-model="beginTime"
          :editable="false"
          :clearable="false"
          @change="changebeginTime"
          prefix-icon=""
          :picker-options="{
            start: '00:00',
            step: '00:05',
            end: '24:00'
    }">
        </el-time-select>
        <el-time-select
          placeholder="结束时间"
          v-model="endTime"
          :editable="false"
          :clearable="false"
          @change="changeendTime"
          :picker-options="{
            start: '00:00',
            step: '00:05',
            end: '24:00',
            minTime: beginTime
    }">
        </el-time-select>
      </div>
      <div class="distance-time ">
        <div>骑行开始时间：{{startTime}}</div>
        <div>骑行结束时间：{{finishTime}}</div>
      </div>
    </div>
    <div class="play">
      <div class="play-box">
        <div class="block">
          <el-slider v-model="percent" style="margin-top: 16px" :max="paths>0?paths-1:0" @change="changslide"></el-slider>
        </div>
        <div class="optbtn">
          <el-button type="primary" @click="pause" v-if="Play">暂停</el-button>
          <el-button type="primary" @click="playing" v-else>继续</el-button>
          <el-button type="success" @click="replay">重播</el-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script type="text/babel">
  import Mainmap from '@/components/Mainmap'
  import Calendar from '@/components/Calendar'
  import {getTrack} from '@/api/map'
  import {getDistance} from '@/api/request'
  import {wgs84togcj02,gcj02tobd09,formatTime} from '@/utils/index'

  export default {
    name:'Tracks',
    data() {
      return{
        map:null,
        timer1:null,
        timer2:null,
        timer3:null,
        list:[],
        data:[],
        paths:0,
        percent:0,
        label:null,
        carMk:null,
        newpoints:[],
        markArray:[],
        Play:true,
        listLoading:false,
        beginTime: '00:00',
        endTime: '23:59',
        beginTimes: '00:00',
        endTimes: '23:59',
        duration:'0',
        date: formatTime(new Date()).slice(0,10),
        startTime:'',
        finishTime:''
      }
    },
    components:{
      Mainmap,
      Calendar
    },
    methods:{
      initmap(map){
        this.map=map;
        this.refresh()
      },
      refresh(){
        this.querytrack(`${this.date} ${this.beginTimes}:00`,`${this.date} ${this.endTimes}:00`)
        this.getdistances(formatTime(new Date()).slice(0,10))
      },
      goback(){
        this.$router.push({ path: '/monitor' })
      },
      querytrack(beginTime,endTime){
        this.map.clearOverlays();
        this.percent=0
        this.Play=true
        this.data=[]
        this.newpoints=[]
        this.listLoading = true;
        let query={
          beginTime:beginTime,
          endTime:endTime,
          trackerId:this.$route.query.trackerId
        }
        let that=this
        getTrack(query).then( response => {
          if(response && response.body){
            this.list = response.body||[];
            this. draw(this.list);
            this.startTime=formatTime(new Date(this.list[0].localTime))
            this.finishTime=formatTime(new Date(this.list[this.list.length-1].localTime))
            }else {
            function myFun(result){
              let cityName = result.name;
              that.map.setCenter(cityName);
            }
            let myCity = new BMap.LocalCity();
            myCity.get(myFun);
          }
          this.listLoading = false
        })
      },
      draw(points){
        let that=this;
        if(points.length>0){
          let data=[],pts,j,k=0;
          for(let i=0;i<points.length;i++){
            if(points[i].lng && points[i].lng>0){
              points[i].times=0
              if(i+1<points.length){
                if(points[i+1].localTime-points[i].localTime>=3600000){
                   j=i
                   points[i].times=k
                   k++;
                }
              }
              if(j && i>j){
                points[i].times=k
              }
              if(points[i].pointType==0){
                pts=new BMap.Point(points[i].lng,points[i].lat);
              }else {
                let pin=wgs84togcj02(points[i].lng,points[i].lat);
                let newPonit=gcj02tobd09(pin[0],pin[1]);
                pts=new BMap.Point(newPonit[0],newPonit[1]);
              }
              data.push(pts);
              that.newpoints.push(points[i])
            }
          }
          that.data = data;
          /*** 本地路线开始* **/
         let CanvasTraces= require ('./canvansTrace')
          new CanvasTraces.CanvasTrace({
          color: "red",
          width: 7,
          showArrow: false,
          showAnimation: false,
           data: data,
           map: this.map,
           points:points,
           zIndex:-1
          });
          /*** 本地路线结束* **/

          /*** 永川路线开始* **/
          // function draw_line_direction(weight){
          //   let icons=new BMap.IconSequence(
          //     new BMap.Symbol('M0 -8 L-5 -3 L0 -5 L5 -2 Z', {
          //       scale: weight/8,
          //       strokeWeight:2,
          //       rotation: 0,
          //       fillColor: 'white',
          //       fillOpacity: 1,
          //       strokeColor:'white'
          //     }),'100%','1%',false);
          //   return icons;
          // }
          //
          // let polyline = new BMap.Polyline(data, {
          //   icons : [draw_line_direction(5)],
          //   strokeColor: '#d81e06',//设置颜色
          //   strokeWeight: 6, //宽度
          //   strokeOpacity: 1
          // });
          // that.map.addOverlay(polyline);
          /*** 永川路线结束* **/

          this.drawIcon(data[0],data[data.length-1],data);  //设置marker
          this.map.setViewport(data);    //调整视野
        }
      },
      drawIcon(start,end,data){
        let that=this;
        let img=[require('../../assets/ridingtrack/start.png'),require('../../assets/ridingtrack/end.png')];
        let myIcon1 = new BMap.Icon(img[0], new BMap.Size(30,90));
        let marker1 = new BMap.Marker(start,{icon:myIcon1});  // 创建标注
        let myIcon2 = new BMap.Icon(img[1], new BMap.Size(30,90));
        let marker2 = new BMap.Marker(end,{icon:myIcon2});  // 创建标注
        marker1.setZIndex(9999);
        marker2.setZIndex(9999);
        this.map.addOverlay(marker1);
        this.map.addOverlay(marker2);
        if(data)  this.timer3=setTimeout(that.run(),1500);//延迟1.5秒运行
      },
      infowindow(points,addr){
        let time='';
        if(points.localTime) time=formatTime(new Date(points.localTime));

        let html = `<div class='guiji_ceng'>
        <div class='b d1'>
         <div onclick="closelabel()" class="closelabelBox"><span class="closelabelBtn"></span></div>
          <b class="device_details"><span class="device_title" >车牌号:</span><span>${''}</span> </b></br>
          <b class="device_details"> <span  class="device_title">速度:</span><span>${points.speed>0?parseInt(points.speed):0}km/h</span> </b></br>
          <b class="device_details"><span class="device_title">通信信号:</span><span>${points.rssi||''}</span> </b></br>
          <b class="device_details"><span class="device_title">GPS信号:</span><span>${points.satellites||''}</span> </b></br>
          <b class="device_details"> <span  class="device_title">经纬度:</span><span>${points.lng},${points.lat}</span></b></br>
          <b>地址:${addr}</b></br>
          <b class="device_details"><span class="device_title">最后上传时间:</span><span>${time}</span> </b></br>
          <b class="device_details"> <span  class="device_title">IMEI号:</span><span>${''}</span> </b></br>
          <b class="device_details"><span class="device_title">使用人:</span>${''}<span></span> </b></br>
        </div>
        <div> <span class='guiji_sanjiao'></span>
        <span class='guiji_sanjiao_2'></span></div>
        </div>`;
        return html
      },
      run(){
        let that=this;
        let myIcon = new BMap.Icon(require('../../assets/move.png'), new BMap.Size(32, 70), {
          imageOffset: new BMap.Size(0, 0)
        });

        that.carMk = new BMap.Marker(that.data[0],{icon:myIcon});
        that.map.addOverlay(that.carMk);
        let opts = {
          position :that.data[0],    // 指定文本标注所在的地理位置
          offset : new BMap.Size(0, -70)    //设置文本偏移量
        };
        that.label = new BMap.Label(that.infowindow(that.newpoints[0]||{},''), opts);  // 创建文本标注对象
        that.label.setStyle({
          color : "#000000",
          background:"none",
          border:"none",
          fontSize : "12px"
        });
        that.map.addOverlay(that.label);
        that.timer2=setTimeout(function(){
          that.resetMkPoint(2);
        },50)
      },
      resetMkPoint:function(i){
      let that=this;
      let geoc = new BMap.Geocoder();
      this.paths  = this.data.length;
      if(i < this.paths){
        let addr='';
        geoc.getLocation(that.data[i], function(rs){
          if(rs){
            addr = rs.address;
          }
          that.geocAdd(addr,i)
        });
      }
    },
      /*** 运行地址 * **/
      geocAdd(addr,i){
      let that=this;
        that.carMk.setPosition(that.data[i]);
        that.carMk.setZIndex(99999);
        that.label.setPosition(that.data[i]);
        that.label.setContent(that.infowindow(that.newpoints[i] || {},addr));
      /**
       * 关闭label
       * **/
      window.closelabel=function(){
        that.label.setStyle({display:"none" });
      };
      /**
       * 打开label
       * **/
      that.carMk.addEventListener("click",function(e){
        that.label.setStyle({display:"block"})
      });

      window.clearTimeout(that.timer1);
      if(that.Play)  that.timer1=setTimeout(function(){
        if(i < that.paths) i++;//判断是否位置增加
        that.resetMkPoint(i,that);
        that.percent=i
      },200);
     },
      pause(){
        this.Play=false;
        this.resetMkPoint(this.percent)
       },
      playing(){
        this.Play=true;
        this.resetMkPoint(this.percent)
     },
      replay(){
        this.Play=true;
        window.clearTimeout(this.timer1);
        this.resetMkPoint(0);
      },
      changslide(val){
        window.clearTimeout(this.timer1);
        this.percent=val;
        this.resetMkPoint(val)
      },
      clickDay(date){
     this.date=date
     this.querytrack(`${this.date} ${this.beginTimes}:00`,`${this.date} ${this.endTimes}:00`)
   },
      changeDate(date){
        this.getdistances(date)
     },
      getdistances(month){
       let that=this;
       // that.listLoading = true
       let query={
         trackerId:this.$route.query.trackerId,
         month:month
       }
       getDistance(query).then( response => {
         that.markArray=response.body||[]
         // that.listLoading = false
       })
    },
      changebeginTime(e){
       this.beginTimes=e
       this.querytrack(`${this.date} ${e}:00`,`${this.date} ${this.endTimes}:00`)
     },
      changeendTime(e){
        this.endTimes=e
        this.querytrack(`${this.date} ${this.beginTimes}:00`,`${this.date} ${e}:00`)
      },
  }
}
</script>
